package com.yuji.aacar.controller.fragment.home;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yuji.aacar.R;
import com.yuji.aacar.base.BaseFragment;
import com.yuji.aacar.base.Const;
import com.yuji.aacar.base.EventConst;
import com.yuji.aacar.base.UserCenter;
import com.yuji.aacar.bean.beans.Banner;
import com.yuji.aacar.bean.response.BannerResponse;
import com.yuji.aacar.bean.response.LoginResponse;
import com.yuji.aacar.bean.response.OrderDetailResponse;
import com.yuji.aacar.bean.response.OrderListResponse;
import com.yuji.aacar.bean.response.OrderSelectResponse;
import com.yuji.aacar.bean.response.VersionResponse;
import com.yuji.aacar.bean.response.WashCarIndexResponse;
import com.yuji.aacar.controller.message.MessageActivity;
import com.yuji.aacar.controller.order.WriteOrderActivity;
import com.yuji.aacar.controller.webview.WebViewActivity;
import com.yuji.aacar.core.cores.event.CoreEventBusMessage;
import com.yuji.aacar.core.cores.event.CoreEventCenter;
import com.yuji.aacar.core.cores.fres.CoreImageLoader;
import com.yuji.aacar.core.cores.fres.listener.IResult;
import com.yuji.aacar.core.cores.services.CoreServiceResponse;
import com.yuji.aacar.service.BaseServiceMediator;
import com.yuji.aacar.service.BaseServiceParams;
import com.yuji.aacar.widgets.autolayout.AutoLinearLayout;
import com.yuji.aacar.widgets.autolayout.AutoRelativeLayout;
import com.yuji.aacar.widgets.bannerview.BannerView;
import com.yuji.aacar.widgets.dialogue.VersionDialog;
import com.yuji.aacar.widgets.textview.PingFangTextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * <li>Package:com.yuji.aacar.controller.fragments.home</li>
 * <li>Author: lining </li>
 * <li>Date: 2018/2/28</li>
 * <li>Description:   </li>
 */

public class HomeFragment extends BaseFragment {


    @BindView(R.id.title_content_home_fragment)
    TextView titleContentHomeFragment;
    @BindView(R.id.message_home_fragment)
    ImageView messageHomeFragment;
    @BindView(R.id.home_fragment_bannerview)
    BannerView homeFragmentBannerview;
    @BindView(R.id.home_fragment_imediate_button)
    AutoLinearLayout homeFragmentImediateButton;
    @BindView(R.id.home_fragment_imediate_one_tv)
    PingFangTextView homeFragmentImediateOneTv;
    @BindView(R.id.home_fragment_imediate_two_tv)
    PingFangTextView homeFragmentImediateTwoTv;
    @BindView(R.id.home_fragment_imediate_button_al)
    AutoRelativeLayout homeFragmentImediateButtonAl;
    @BindView(R.id.home_fragment_reserve_button)
    AutoLinearLayout homeFragmentReserveButton;
    @BindView(R.id.home_fragment_reserve_one_tv)
    PingFangTextView homeFragmentReserveOneTv;
    @BindView(R.id.home_fragment_reserve_two_tv)
    PingFangTextView homeFragmentReserveTwoTv;
    @BindView(R.id.home_fragment_reserve_button_al)
    AutoRelativeLayout homeFragmentReserveButtonAl;
    @BindView(R.id.home_fragment_tuxiang)
    ImageView homeFragmentTuxiang;
    @BindView(R.id.home_fragment_wendu)
    PingFangTextView homeFragmentWendu;
    @BindView(R.id.home_fragment_tianqi)
    PingFangTextView homeFragmentTianqi;
    @BindView(R.id.home_fragment_xichedu)
    PingFangTextView homeFragmentXichedu;
    @BindView(R.id.home_fragment_weather_ll)
    AutoLinearLayout homeFragmentWeatherLl;
    @BindView(R.id.home_fragment_all_rl)
    RelativeLayout homeFragmentAllRl;
//    private int[] imgs = {R.drawable.a};
    //    private int[] imgs = {R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d};
    private List<View> viewList;

    private HomeFragmentVM homeFragmentVM;

    private WashCarIndexResponse washCarIndexResponse;
    private ArrayList<Banner> banners;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case BaseServiceMediator.GET_WASH_INDEX_CODE:
                    if (null != washCarIndexResponse){
                        if (null != washCarIndexResponse.getWealth()){
                            homeFragmentTuxiang.setImageResource(getBitMapAccordingTheWeather(washCarIndexResponse.getWealth()));
                        }
                        String low = washCarIndexResponse.getLow();
                        String high = washCarIndexResponse.getHigh();
                        if (null != low && null != high){
                            homeFragmentWendu.setText(low+"~"+high+"℃");
                        }

                        if (null != washCarIndexResponse.getWealth()){
                            homeFragmentTianqi.setText(washCarIndexResponse.getWealth());
                        }
                        if (null != washCarIndexResponse.getWashIndex()){
                            homeFragmentXichedu.setText(washCarIndexResponse.getWashIndex()+"洗车");
                        }
                    }
                    break;

                case BaseServiceMediator.GET_HOMEPAGE_BANNER_CODE:
                    restBannerView();
                    break;
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void alreadyBindBaseViewModel() {
        super.alreadyBindBaseViewModel();
        homeFragmentVM = (HomeFragmentVM) coreBaseViewModel;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View rootView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_home, null);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void showFragemt() {
        super.showFragemt();

    }

    private void restBannerView() {
        if (null != banners){
            viewList = new ArrayList<View>();
            for (int i = 0; i < banners.size(); i++) {
                View bannerView = LayoutInflater.from(getActivity()).inflate(R.layout.activity_banner_view, null);
                ImageView iv = (ImageView) bannerView.findViewById(R.id.banner_image);
                Banner banner = banners.get(i);
                CoreImageLoader.loadImage(getActivity(), banner.getImageUrl(), new IResult<Bitmap>() {
                    @Override
                    public void onResult(Bitmap result) {
                        iv.setImageBitmap(result);
                    }
                });
                bannerView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        presentControllerFromFragment(WebViewActivity.class,getActivity().getIntent().putExtra("url",banner.getImgDetailHtml()));
                    }
                });
                viewList.add(bannerView);
            }
            homeFragmentBannerview.startLoop(true);
            homeFragmentBannerview.setLoopInterval(Integer.MAX_VALUE);
            homeFragmentBannerview.setViewList(viewList);
        }
    }


    private void requestBanner() {
        requestParams = BaseServiceParams.getHomePageBanner();
        doTask(BaseServiceMediator.GET_HOME_BANNER);
    }

    private void requestWeather() {
        requestParams = BaseServiceParams.getWashIndex("上海");
        doTask(BaseServiceMediator.GET_WASH_INDEX);
    }

    @OnClick({R.id.title_content_home_fragment, R.id.message_home_fragment, R.id.home_fragment_bannerview, R.id.home_fragment_imediate_button, R.id.home_fragment_imediate_one_tv, R.id.home_fragment_imediate_two_tv, R.id.home_fragment_imediate_button_al, R.id.home_fragment_reserve_button, R.id.home_fragment_reserve_one_tv, R.id.home_fragment_reserve_two_tv, R.id.home_fragment_reserve_button_al, R.id.home_fragment_all_rl})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_content_home_fragment:
                break;
            case R.id.message_home_fragment:
                presentControllerFromFragment(MessageActivity.class);
                LoginResponse user = UserCenter.getCurrentUser();
                if (null != user){
                    UserCenter.setNewMessage(user.getMemberId(),"0");
                    CoreEventCenter.postMessage(EventConst.PUSH_MESSAGE_CHECKED, "xiaoxi");
                }
                break;
            case R.id.home_fragment_bannerview:
                break;
            case R.id.home_fragment_imediate_button:
                toNestStep(1);
                break;
            case R.id.home_fragment_imediate_one_tv:
                toNestStep(1);
                break;
            case R.id.home_fragment_imediate_two_tv:
                toNestStep(1);
                break;
            case R.id.home_fragment_imediate_button_al:
                toNestStep(1);
                break;
            case R.id.home_fragment_reserve_button:
                toNestStep(2);
//                presentControllerFromFragment(OrderPayMoreActivity.class);
                break;
            case R.id.home_fragment_reserve_one_tv:
                toNestStep(2);
                break;
            case R.id.home_fragment_reserve_two_tv:
                toNestStep(2);
                break;
            case R.id.home_fragment_reserve_button_al:
                toNestStep(2);
                break;
            case R.id.home_fragment_all_rl:
                break;
        }
    }

    @Override
    public void requestSuccess(CoreServiceResponse response) {
        super.requestSuccess(response);

        if (response.getRequestCode() == BaseServiceMediator.GET_HOMEPAGE_BANNER_CODE){
            BannerResponse bannerResponse = (BannerResponse) response.getResponse();
            banners = bannerResponse.getBanners();
            mHandler.sendEmptyMessage(BaseServiceMediator.GET_HOMEPAGE_BANNER_CODE);
            requestWeather();
        } else if (response.getRequestCode() == BaseServiceMediator.GET_WASH_INDEX_CODE){
            washCarIndexResponse = (WashCarIndexResponse) response.getResponse();
            mHandler.sendEmptyMessage(BaseServiceMediator.GET_WASH_INDEX_CODE);
//            requestPrice();
        } else if (response.getRequestCode() == BaseServiceMediator.SELECT_CODE) {
            OrderSelectResponse selectResponse = (OrderSelectResponse) response.getResponse();
//            requestSubmitOrder();
//            requestOrderList();
//            requestOrderDetail();
//            requestAliGen();
        } else if (response.getRequestCode() == BaseServiceMediator.LIST_CODE) {
            OrderListResponse submitResponse = (OrderListResponse) response.getResponse();
        } else if (response.getRequestCode() == BaseServiceMediator.DETAIL_CODE) {
            OrderDetailResponse submitResponse = (OrderDetailResponse) response.getResponse();
        }else if (response.getRequestCode() == BaseServiceMediator.ALI_GEN_CODE) {
        }
    }



    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            resetMessageStatus();
            requestBanner();
        }
    }

    private void resetMessageStatus() {
        LoginResponse user = UserCenter.getCurrentUser();
        if (null != user){
           String has = UserCenter.getNewMessage(user.getMemberId());
            if (has.contentEquals("1")){
                messageHomeFragment.setImageResource(R.mipmap.message_new_normal);
            } else {
                messageHomeFragment.setImageResource(R.mipmap.message_no_normal);
            }
        }
    }


    @Override
    public void requestFailed(CoreServiceResponse response) {
        super.requestFailed(response);
    }

    private void toNestStep(int type) {
        LoginResponse user = UserCenter.getCurrentUser();
        if (null != user) {
            switch (type){
                case 1:

//                    String[] times = TimeUtils.getSystemWashTime().split(":");
//                    if (Integer.parseInt(times[0]) > 21){
//                        DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                            }
//                        };
//                        showAlertSingleButtonDialogue(getActivity(), "当天工作截止了", "请预约明天洗车", "我知道了",clickListener);
//
//                    } else {
//
//                        if (UserCenter.isFirstClickImmediateWash(user.getMemberId())){
//                            DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    JumpToOrder(1);
//                                }
//                            };
//                            showAlertSingleButtonDialogue(getActivity(), "即时洗车", "2小时内必达", "我知道了",clickListener);
//                        } else {
//                            JumpToOrder(1);
//                        }
//
//                        shortImediateButtonSelect();
//                    }


                    if (UserCenter.isFirstClickImmediateWash(user.getMemberId())){
                        DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                UserCenter.setFirstClickImmediateWash(user.getMemberId());
                                JumpToOrder(Const.WASH_TYPE_IMMEDIATE);
                            }
                        };
                        showAlertSingleButtonDialogue(getActivity(), "即时洗车", "2小时内必达", "我知道了",clickListener);
                    } else {
                        JumpToOrder(Const.WASH_TYPE_IMMEDIATE);
                    }

                    shortImediateButtonSelect();


                    break;
                case 2:

                    if (UserCenter.isFirstClickReserveWash(user.getMemberId())){
                        DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                UserCenter.setFirstClickReserveWash(user.getMemberId());
                                JumpToOrder(Const.WASH_TYPE_RESERVE);
                            }
                        };
                        showAlertSingleButtonDialogue(getActivity(), "预约洗车请预留更多时间", "价格更优惠", "我知道了",clickListener);
                    } else {
                        JumpToOrder(Const.WASH_TYPE_RESERVE);
                    }

                    shortReserveButtonSelect();
                    break;
            }
        }

//        presentControllerFromFragment(DirtyActivity.class);
    }

    private void JumpToOrder(int type){
        Intent intent = getActivity().getIntent();
        intent.putExtra("washType",type);
        intent.putExtra("orderType",0);
        presentControllerFromFragment(WriteOrderActivity.class, intent);
    }

    private void shortImediateButtonSelect() {
        homeFragmentImediateButton.setPressed(true);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                homeFragmentImediateButton.setPressed(false);
            }
        }, 50);

    }

    private void shortReserveButtonSelect() {
        homeFragmentReserveButton.setPressed(true);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                homeFragmentReserveButton.setPressed(false);
            }
        }, 50);

    }

    private int getBitMapAccordingTheWeather(String wealth) {
        int drawable = R.mipmap.clouday;
        if (wealth.indexOf("晴") >= 0){
            drawable = R.mipmap.sunday;
        } else if (wealth.indexOf("雨") >= 0) {
            drawable =R.mipmap.rainday;
        }else if (wealth.indexOf("阴") >= 0) {
            drawable = R.mipmap.clouday;
        }else if (wealth.indexOf("雪") >= 0) {
            drawable = R.mipmap.snowday;
        }
        return drawable;
    }

    @Override
    public void handleMessage(CoreEventBusMessage message) {
        super.handleMessage(message);
        if (message.getMessageCode().contentEquals(String.valueOf(EventConst.VERSION_UPDATE))) {
            if (!isHidden()){
                VersionResponse intent = (VersionResponse) message.getMessageObjects();
                if (intent.getFlag().contentEquals("1")) {
                    VersionDialog dialog = new VersionDialog(getActivity(), intent);
                    if (!dialog.isShowing()) {
                        dialog.showDialog();
                    }
                }
            }
        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.PUSH_MESSAGE))) {
            if (!isHidden()){
                messageHomeFragment.setImageResource(R.mipmap.message_new_normal);
            }

        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.PUSH_MESSAGE_CHECKED))) {
            if (!isHidden()){
                messageHomeFragment.setImageResource(R.mipmap.message_no_normal);
            }
        }
    }
}
